<template>
	<view class="rootview">
		<uni-list>
			<uni-list-item v-for="item in listData" :key="item._id" :title="item.name" link :to="'../detail/detail?id='+item._id"></uni-list-item>
		</uni-list>
		<uni-load-more :status="loadMoreStatus" :icon-size="16" :content-text="loadMoreText" />
		<uni-fab @fabClick="toAdd"></uni-fab>
	</view>
</template>

<script>
	import db from '@/js_sdk/uni-clientDB/index.js'
	const dbCmd = db.command
	const pageSize = 15 //列表分页常量
	export default {
		data() {
			return {
				listData: [],
				loadMoreStatus: 'more',
				loadMoreText: {
					contentdown: '上拉加载更多',
					contentrefresh: '加载中',
					contentnomore: '没有更多'
				},
				lastId: '',
				lastName: ''
			}
		},
		onLoad() {
			this.getList()
			uni.$on('reloadList', this.getList)
		},
		onUnload() {
			uni.$off('reloadList', this.getList)
		},
		onPullDownRefresh() {
			this.lastId = ''
			this.lastName = ''
			this.getList(true);
		},
		onReachBottom() {
			this.loadMoreStatus = 'more';
			this.getList(false);
		},
		methods: {
			getList(reload = true) { // 参数reload值为true时执行列表初始化逻辑，值为false时执行追加下一页数据的逻辑。默认为true
				var that = this
				if(reload) {
					// 重置游标
					this.lastId = ''
					this.lastName = ''
				}
				that.loadMoreStatus = 'loading';
				uniCloud.callFunction({
					name: 'uni-clientDB',
					data: {
						command: db.collection('phonebook').where(dbCmd.or({ //修改需要访问的表名、设置where查询条件
							name: dbCmd.gt(that.lastName)
						}, {
							name: dbCmd.eq(that.lastName),
							_id: dbCmd.gt(that.lastId)
						})).orderBy("name", "asc").limit(pageSize).get() //在orderBy里设置排序字段和正序/倒叙
					},
					success(res) {
						console.log(res);
						const newList = res.result.data
						if (!newList) {
							uni.showModal({
								content: res.result.msg || '获取列表失败',
								showCancel: false
							})
							return
						}
						console.log(newList);
						if (newList.length < pageSize) {
							that.loadMoreStatus = 'noMore';
						} else {
							that.loadMoreStatus = 'more';
						}
						that.listData = reload ? newList : that.listData.concat(newList);
						if (newList.length > 0) {
							const lastItem = newList[newList.length - 1]
							that.lastId = lastItem._id;
							that.lastName = lastItem.name;
						}

					},
					fail(err) {
						console.error(err)
						uni.showModal({
							content: err.message || '服务器连接失败',
							showCancel: false
						})
					},
					complete() {
						uni.stopPullDownRefresh()
					}
				})
			},
			toAdd() {
				uni.navigateTo({
					url: "../add/add"
				})
			}
		}
	}
</script>

<style>
	.rootview {
		padding: 15px;
	}
</style>
